package org.dromara.authcode.service.impl;

import org.dromara.authcode.domain.TDevice;
import org.dromara.authcode.service.ITDeviceService;
import org.dromara.authcode.util.GaodeMapUtil;
import org.dromara.common.core.utils.DateUtils;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.dromara.authcode.domain.bo.TDeviceLocationBo;
import org.dromara.authcode.domain.vo.TDeviceLocationVo;
import org.dromara.authcode.domain.TDeviceLocation;
import org.dromara.authcode.mapper.TDeviceLocationMapper;
import org.dromara.authcode.service.ITDeviceLocationService;

import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 设备位置记录Service业务层处理
 *
 * @author Miles Meng
 * @date 2025-08-11
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class TDeviceLocationServiceImpl implements ITDeviceLocationService {
    private final TDeviceLocationMapper baseMapper;
    private final ITDeviceService deviceService;
    private final GaodeMapUtil mapUtil;

    /**
     * 查询设备位置记录
     *
     * @param id 主键
     * @return 设备位置记录
     */
    @Override
    public TDeviceLocationVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询设备位置记录列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 设备位置记录分页列表
     */
    @Override
    public TableDataInfo<TDeviceLocationVo> queryPageList(TDeviceLocationBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<TDeviceLocation> lqw = buildQueryWrapper(bo);
        Page<TDeviceLocationVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的设备位置记录列表
     *
     * @param bo 查询条件
     * @return 设备位置记录列表
     */
    @Override
    public List<TDeviceLocationVo> queryList(TDeviceLocationBo bo) {
        LambdaQueryWrapper<TDeviceLocation> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<TDeviceLocation> buildQueryWrapper(TDeviceLocationBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<TDeviceLocation> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getDeviceId() != null, TDeviceLocation::getDeviceId, bo.getDeviceId());
        lqw.eq(bo.getLatitude() != null, TDeviceLocation::getLatitude, bo.getLatitude());
        lqw.eq(bo.getLongitude() != null, TDeviceLocation::getLongitude, bo.getLongitude());
        lqw.eq(bo.getAccuracy() != null, TDeviceLocation::getAccuracy, bo.getAccuracy());
        lqw.eq(bo.getAltitude() != null, TDeviceLocation::getAltitude, bo.getAltitude());
        lqw.eq(bo.getSpeed() != null, TDeviceLocation::getSpeed, bo.getSpeed());
        lqw.eq(bo.getBearing() != null, TDeviceLocation::getBearing, bo.getBearing());
        lqw.eq(bo.getLocationTime() != null, TDeviceLocation::getLocationTime, bo.getLocationTime());
        lqw.eq(bo.getRecordTime() != null, TDeviceLocation::getRecordTime, bo.getRecordTime());
        lqw.eq(StringUtils.isNotBlank(bo.getAddress()), TDeviceLocation::getAddress, bo.getAddress());
        return lqw;
    }

    /**
     * 新增设备位置记录
     *
     * @param bo 设备位置记录
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(TDeviceLocationBo bo) {
        TDeviceLocation add = MapstructUtils.convert(bo, TDeviceLocation.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改设备位置记录
     *
     * @param bo 设备位置记录
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(TDeviceLocationBo bo) {
        TDeviceLocation update = MapstructUtils.convert(bo, TDeviceLocation.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(TDeviceLocation entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除设备位置记录信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    /**
     * 获取设备最后位置,入库
     *
     * @param dto 设备mac地址
     * @return 设备位置记录
     */
    @Override
    public Boolean recordDeviceLocation(TDeviceLocationBo dto) {
        // 检查设备是否存在
        TDevice device = deviceService.queryByMacAddress(dto.getMacAddress());
        // 设备不存在
        if (device == null) {
            log.error("设备不存在，MAC地址: {}", dto.getMacAddress());
            return false;
        }
        // 获取地址信息
        if (dto.getLongitude() == null || dto.getLatitude() == null) {
            log.error("经纬度不能为空");
            return false;
        }
        if (dto.getAddress() == null || dto.getAddress().isEmpty()) {
            dto.setAddress(mapUtil.getAddress(dto.getLongitude(), dto.getLatitude()));
        }
        // 保存位置记录
        TDeviceLocation location = new TDeviceLocation();
        location.setDeviceId(device.getId());
        location.setLatitude(dto.getLatitude());
        location.setLongitude(dto.getLongitude());
        location.setAccuracy(dto.getAccuracy());
        location.setAltitude(dto.getAltitude());
        location.setSpeed(dto.getSpeed());
        location.setBearing(dto.getBearing());
        if (dto.getLocationTime() != null) {
            location.setLocationTime(dto.getLocationTime());
        } else {
            location.setLocationTime(DateUtils.getNowDate());
        }
        location.setRecordTime(DateUtils.getNowDate());
        location.setAddress(dto.getAddress());
        return baseMapper.insert(location) > 0;
    }

    /**
     * 获取最后一次位置信息
     *
     * @param macAddress mac地址
     * @return 位置信息
     */
    @Override
    public TDeviceLocationVo getLastLocationByMac(String macAddress) {
        TDevice device = deviceService.queryByMacAddress(macAddress);
        // 设备不存在
        if (device == null) {
            log.error("设备不存在，MAC地址: {}", macAddress);
            return null;
        }

        LambdaQueryWrapper<TDeviceLocation> lqw = buildQueryWrapper(new TDeviceLocationBo());
        lqw.eq(TDeviceLocation::getDeviceId, device.getId());
        lqw.orderByDesc(TDeviceLocation::getRecordTime);
        lqw.last("limit 1");

        TDeviceLocation location = baseMapper.selectOne(lqw);

        if (location == null) {
            return null;
        }
        TDeviceLocationVo vo = MapstructUtils.convert(location, TDeviceLocationVo.class);
        if (vo != null) {
            vo.setDeviceName(device.getAlias());
        }
        return vo;
    }
}
